package com.pozu.new_retail.controllers;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pozu.new_retail.dao.base.JsonResult;
import com.pozu.new_retail.dao.model.AppSetting;
import com.pozu.new_retail.dao.model.Goods;
import com.pozu.new_retail.dao.model.GoodsExt;
import com.pozu.new_retail.dao.model.Order;
import com.pozu.new_retail.dao.model.ShoppingCart;
import com.pozu.new_retail.dao.model.User;
import com.pozu.new_retail.dao.pay.wx.WXClientPayRequestInfo;
import com.pozu.new_retail.dao.pay.wx.WXPrePayReturns;
import com.pozu.new_retail.service.AppSettingService;
import com.pozu.new_retail.service.CodeService;
import com.pozu.new_retail.service.GoodsExtService;
import com.pozu.new_retail.service.GoodsService;
import com.pozu.new_retail.service.OrderService;
import com.pozu.new_retail.service.ShoppingCartService;
import com.pozu.new_retail.service.UserService;
import com.pozu.new_retail.utils.CodeConstants;
import com.pozu.new_retail.utils.CodeProperties;
import com.pozu.new_retail.utils.LogUtils;
import com.pozu.new_retail.utils.PayTools;
import com.pozu.new_retail.utils.Tools;

@Controller
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private GoodsExtService goodsExtService;
	@Autowired
	private AppSettingService appSettingService;
	@Autowired
	private CodeService codeService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserService userService;

	/**
	 * 微信支付
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/pay", method = RequestMethod.POST)
	public Object wxAddOrder(HttpServletRequest request) throws Exception{		
		
		int appId = request.getHeader("appId")==null?1:Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		AppSetting appSetting = appSettingService.queryByAppId(appId);
		
		Map<String, Object> map = Tools.getRequestData(request);

		String orderId = map.get("orderId").toString();	

		//获取用户的openId
		String js_code = map.get("js_code").toString();
		
		Map<String, String> hashMap = PayTools.getOpenIdAnUUID(js_code,appSetting.getWxAppId(),appSetting.getAppSecret());
		
		String openId = hashMap.get("openId");
		
		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		
		if (order.getOrderType() == 2) {
			
			if (System.currentTimeMillis() < order.getPreStartTime()) {
				jr.respCode = CodeConstants.PRESALEPAYTIMING_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.PRESALEPAYTIMING_MSG);
				return jr;
			}
			
			if (System.currentTimeMillis() > order.getPreStartTime() + order.getPrePayLimitDays()*24*3600*1000) {
				jr.respCode = CodeConstants.PRESALEPAYTIMEOUT_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.PRESALEPAYTIMEOUT_MSG);
				return jr;
			}
			
			int payNumber = orderService.queryCountByOrderId(orderId);
			
			if (order.getPreMinNumber() > payNumber) {
				jr.respCode = CodeConstants.PRESALEFAILED_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.PRESALEFAILED_MSG);
				return jr;
			}
			
		}
		
		
		Order tempOrder = new Order();
		tempOrder.setOrderId(orderId);
		tempOrder.setOpenId(openId);
		
		if(order.getMoney()==0){
			
			jr.respCode = CodeConstants.SUCCESS_CODE;
			jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
			tempOrder.setOrderState(1);
			
		}else {
			
			order.setSpbill_create_ip(request.getRemoteHost());
			order.setOpenId(openId);

			WXPrePayReturns ppr = orderService.wxAddOrder(order,appSetting.getWxAppId(),appSetting.getMchId(),appSetting.getMchKey());
			
			if(ppr.getReturn_code().equals("FAIL")){
				jr.respCode = CodeConstants.ORDERERROR_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.ORDERERROR_MSG);
				LogUtils.ERROR.error("失败原因,{}",ppr.getReturn_msg());
				return jr;
			}
			if( ppr.getResult_code().equals("FAIL")){
				jr.respCode = CodeConstants.ORDERERROR_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.ORDERERROR_MSG);
				LogUtils.ERROR.error("微信支付下单失败");
				return jr;
			}
			
			//接受到微信返回的结果后,如果返回正确信息则,把客户端需要的信息组装后发给客户端		
			WXClientPayRequestInfo cpi = new WXClientPayRequestInfo();
			cpi.setAppId(ppr.getAppid());
			cpi.setBody("prepay_id="+ppr.getPrepay_id());
			String nonce_str = PayTools.generateRandCode();//随机字符串
			cpi.setNonceStr(nonce_str);
			cpi.setOrderId(ppr.getOrderId());
			cpi.setTimeStamp((System.currentTimeMillis()/1000)+"");

			cpi.setPaySign(PayTools.createWXClientPayRequestSign(cpi,appSetting.getMchKey()));
			jr.respCode = CodeConstants.SUCCESS_CODE;
			jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
			jr.respData = cpi;
		}
		orderService.updateOrder(tempOrder);
		
		return jr;
	}
	
	/**
	 * 查询微信订单状态
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/checkPay", method = RequestMethod.GET)
	public Object checkWXOrder(HttpServletRequest request) throws Exception{
		
		int appId = request.getHeader("appId")==null?1:Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		AppSetting appSetting = appSettingService.queryByAppId(appId);
	
		JsonResult jr = new JsonResult();

		String orderId =  request.getParameter("orderId");// 订单号
		
		Order order = orderService.queryByOrderId(orderId);
		if(null == order){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			LogUtils.INFO.info("{}充值订单信息不存在",orderId);
			return jr;
		}
		int code = order.getOrderState();
		if(code == 0){
			code = orderService.queryWXOrder(order,appSetting.getWxAppId(),appSetting.getMchId(),appSetting.getMchKey());
		}
		jr.respCode = code;
		jr.respMsg = CodeProperties.getString(code);
		return jr;
	}
	
	/**
	 * 微信支付回调
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/api/orders/callbacks", method = RequestMethod.POST)
	public void wxCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		BufferedReader bufferReader = request.getReader();
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = bufferReader.readLine()) != null) {
			sb.append(line.trim());
		}	
		String returnString = orderService.wxCallBack(sb.toString());
		PayTools.sendXML(response, returnString);
		
	}
	
	/**
	 * 获取订单列表信息
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/list", method = RequestMethod.GET)
	public Object get(HttpServletRequest request) throws Exception{
		
		int appId = request.getHeader("appId")==null?1:Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		JsonResult jr = new JsonResult();

		HashMap<String, Object> map = new HashMap<String, Object>();

		long userId = Long.parseLong(request.getHeader("userId"));

		if(request.getParameter("orderState") != null){
			int orderState = Integer.parseInt(request.getParameter("orderState"));//订单支付状态0待付款1待发货2待收货3待评价
			map.put("orderState", orderState);
			if(orderState == 3){
				map.put("commentState", 1);
			}
			if (orderState == 0) {
				map.put("orderType", 3);
			}
		}
		
		if (!map.containsKey("orderType")) {
			map.put("orderType", 2);
		}

		int pageStart = Integer.parseInt(request.getParameter("pageStart"));//第几页从0开始

		int pageSize = Integer.parseInt(request.getParameter("pageSize"));//一页显示几条数据

		map.put("userId", userId);
		map.put("pageStart", pageStart*pageSize);
		map.put("pageSize", pageSize);
		map.put("appId", appId);

		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = orderService.queryOrderList(map);

		return jr;

	}
	
	/**
	 * 获取退款订单信息
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/refund", method = RequestMethod.GET)
	public Object getRefundOrder(HttpServletRequest request) throws Exception{
		
		int appId = request.getHeader("appId")==null?1:Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		JsonResult jr = new JsonResult();

		HashMap<String, Object> map = new HashMap<String, Object>();

		long userId = Long.parseLong(request.getHeader("userId"));

		int pageStart = Integer.parseInt(request.getParameter("pageStart"));//第几页从0开始

		int pageSize = Integer.parseInt(request.getParameter("pageSize"));//一页显示几条数据

		map.put("userId", userId);
		map.put("pageStart", pageStart*pageSize);
		map.put("pageSize", pageSize);
		map.put("appId", appId);

		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = orderService.queryRefundOrderList(map);

		return jr;

	}
	
	/**
	 * 从购物车选商品下订单
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders", method = RequestMethod.POST)
	public Object add(HttpServletRequest request) throws Exception{
		
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		int channelId = request.getHeader("channelId") == null ? 1 : Integer.parseInt(request.getHeader("channelId"));//渠道
		
		JsonResult jr = new JsonResult();
		
		long userId = Long.parseLong(request.getHeader("userId"));
		
		Map<String, Object> map = Tools.getRequestData(request);
		
		String receiver = map.get("receiver").toString();//收件人
		String phone = map.get("phone").toString();//收件人电话
		String address = map.get("address").toString();//收件人地址
		
		double scores = 0;//积分
		
		if (null != map.get("scores")) {
			scores = Double.parseDouble(map.get("scores").toString());//积分 不使用不填
		}

		if (scores > 0) {
			User user = userService.queryByUserId(userId);
			if (null == user) {
				jr.respCode = CodeConstants.USERNOTEXISTED_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.USERNOTEXISTED_MSG);
				return jr;	
			}
			if (user.getScores() < scores) {
				jr.respCode = CodeConstants.SCORESNOTENOUGH_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.SCORESNOTENOUGH_MSG);
				return jr;	
			}
		}
		
		String  code = null;
		
		if(null!=map.get("code")){
			code = map.get("code").toString();//组团码 不适用不填写
		}
		
		Integer codeDiscount = null;//组团码金额
		
		Integer level = null;
		
		if(null!=code&&!"".equals(code)){
			
			Integer[] discount = codeService.queryDiscountByCode(appId, code,userId);
			
			codeDiscount = discount[1];//组团码优惠%
			level = discount[0];
			
			if(null == codeDiscount) {
				jr.respCode = CodeConstants.CODENOTEXISTED_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.CODENOTEXISTED_MSG);
				LogUtils.ERROR.error(code,",组团码不存在!");
				return jr;				
			}

		}
		
		@SuppressWarnings("unchecked")
		List<Long> ids = (List<Long>) map.get("ids");//购物车中商品的主键id
		
		List<ShoppingCart> carts = new ArrayList<ShoppingCart>();
		
		if(null!=ids&&ids.size()>0){
			for(Object idobjec:ids){
				
				long shoppingCartId = Long.parseLong(idobjec.toString());
				
				ShoppingCart cart = shoppingCartService.queryByShoppingCartId(shoppingCartId);
				
				if (null != cart) {
					carts.add(cart);	
				}
			}
		}	
		int resultCode = shoppingCartService.checkShoppingCarts(carts,codeDiscount);
		if (resultCode != 0) {
			jr.respCode = resultCode;
			jr.respMsg = CodeProperties.getString(resultCode);
			return jr;
		}
		
		AppSetting appSetting = appSettingService.queryByAppId(appId);
		
		double expressMoney = appSetting.getExpressMoney();//快递费金额
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = orderService.saveOrder(carts, userId, receiver, phone, address,appId,channelId,code,level,codeDiscount,expressMoney,scores);
		
		return jr;
		
	}
	
	/**
	 * 直接下订单
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/direct", method = RequestMethod.POST)
	public Object addDirect(HttpServletRequest request) throws Exception{
		
		int appId = request.getHeader("appId")==null?1:Integer.parseInt(request.getHeader("appId"));//那个小程序
		int channelId = request.getHeader("channelId")==null?1:Integer.parseInt(request.getHeader("channelId"));//渠道
		
		JsonResult jr = new JsonResult();
		
		long userId = Long.parseLong(request.getHeader("userId"));
		
		Map<String, Object> map = Tools.getRequestData(request);
		
		String receiver = map.get("receiver").toString();//收件人
		String phone = map.get("phone").toString();//收件人电话
		String address = map.get("address").toString();//收件人地址

		int goodsExtId = Integer.parseInt(map.get("goodsExtId").toString());//商品拓展id
		
		int number = Integer.parseInt(map.get("number").toString());//购买个数
		
		GoodsExt ext = goodsExtService.queryByGoodsExtId(goodsExtId);
		if(null == ext || ext.getState()!=0 || ext.getPrice()<=0){
			jr.respCode = CodeConstants.GOODSNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTEXISTED_MSG);
			return jr;
		}
		
		if(ext.getNumber() < number){
			jr.respCode = CodeConstants.GOODSNOTENOUGH_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTENOUGH_MSG);
			return jr;
		}
		
		int goodsId = ext.getGoodsId();
		
		Goods goods = goodsService.queryInfoByGoodsId(goodsId);
		if(null == goods || goods.getState()!=0){
			jr.respCode = CodeConstants.GOODSNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTEXISTED_MSG);
			return jr;
		}
		
		if (goods.getSaleType() == 0 && System.currentTimeMillis() >= goods.getPreStartTime()) {
			jr.respCode = CodeConstants.PRESALETIMEOUT_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.PRESALETIMEOUT_MSG);
			return jr;
		}
		
		double scores = 0;//积分
		
		if (null != map.get("scores")) {
			scores = Double.parseDouble(map.get("scores").toString());
		}

		if (scores > 0) {
			User user = userService.queryByUserId(userId);
			if (null == user) {
				jr.respCode = CodeConstants.USERNOTEXISTED_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.USERNOTEXISTED_MSG);
				return jr;	
			}
			if (user.getScores() < scores) {
				jr.respCode = CodeConstants.SCORESNOTENOUGH_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.SCORESNOTENOUGH_MSG);
				return jr;	
			}
		}
		
		if (goods.getSaleType() == 0) {
			if (scores > 0) {
				jr.respCode = CodeConstants.PRESALESCORESERROR_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.PRESALESCORESERROR_MSG);
				return jr;
			}
		}
	
		ShoppingCart cart = new ShoppingCart();
		
		cart.setUserId(userId);
		cart.setGoodsExtId(goodsExtId);
		cart.setNumber(number);
		
		if (goods.getGroupFlag() == 1 && goods.getSaleType() == 1) {
			cart.setType(1);
		}else {
			cart.setType(0);
		}
		
		cart.setDiscount(0);
		
		cart.setAppId(appId);
		shoppingCartService.saveShoppingCart(cart);
		
		String code = null;
		
		if(null!=map.get("code")){
			code = map.get("code").toString();//折扣码
		}

		Integer codeDiscount = null;//组团码金额
		
		Integer level = null;
		
		if(null!=code&&!"".equals(code)){
			
			if (cart.getType() != 1) {
				jr.respCode = CodeConstants.CODEUSEDEERROR_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.CODEUSEDEERROR_MSG);
				LogUtils.ERROR.error(goodsId+"",",该商品不能使用组团码!");
				return jr;		
			}
			
			Integer[] discount = codeService.queryDiscountByCode(appId, code,userId);
			
			codeDiscount = discount[1];//组团码优惠%
			
			level = discount[0];
			
			if(null == codeDiscount) {
				jr.respCode = CodeConstants.CODENOTEXISTED_MSG;
				jr.respMsg = CodeProperties.getString(CodeConstants.CODENOTEXISTED_MSG);
				LogUtils.ERROR.error(code,",组团码不存在!");
				return jr;				
			}

		}
		
		List<ShoppingCart> carts = new ArrayList<ShoppingCart>();
		carts.add(cart);
		
		AppSetting appSetting = appSettingService.queryByAppId(appId);
		
		double expressMoney = appSetting.getExpressMoney();//快递费金额
		
		Order  order = orderService.saveOrder(carts, userId, receiver, phone, address,appId,channelId,code,level,codeDiscount,expressMoney,scores); 
		
		if(order.getMoney()==0){
			
			Order tempOrder = new Order();
			
			tempOrder.setOrderId(order.getOrderId());
			
			jr.respCode = CodeConstants.SUCCESS_CODE;
			jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
			
			tempOrder.setOrderState(1);
			orderService.updateOrder(tempOrder);
			
			return jr;
			
		}

		order.setSpbill_create_ip(request.getRemoteHost());
		
		//获取用户的openId
		String js_code = map.get("js_code").toString();
		
		Map<String, String> hashMap = PayTools.getOpenIdAnUUID(js_code,appSetting.getWxAppId(),appSetting.getAppSecret());
		
		String openId = hashMap.get("openId");
		order.setOpenId(openId);
		
		Order temp = new Order();
		temp.setOrderId(order.getOrderId());
		temp.setOpenId(openId);
		orderService.updateOrder(temp);

		WXPrePayReturns ppr = orderService.wxAddOrder(order,appSetting.getWxAppId(),appSetting.getMchId(),appSetting.getMchKey());
		
		if(ppr.getReturn_code().equals("FAIL")){
			jr.respCode = CodeConstants.ORDERERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERERROR_MSG);
			LogUtils.ERROR.error("失败原因,{}",ppr.getReturn_msg());
			return jr;
		}
		if( ppr.getResult_code().equals("FAIL")){
			jr.respCode = CodeConstants.ORDERERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERERROR_MSG);
			LogUtils.ERROR.error("微信支付下单失败");
			return jr;
		}
		
		//接受到微信返回的结果后,如果返回正确信息则,把客户端需要的信息组装后发给客户端		
		WXClientPayRequestInfo cpi = new WXClientPayRequestInfo();
		cpi.setAppId(ppr.getAppid());
		cpi.setBody("prepay_id="+ppr.getPrepay_id());
		String nonce_str = PayTools.generateRandCode();//随机字符串
		cpi.setNonceStr(nonce_str);
		cpi.setOrderId(ppr.getOrderId());
		cpi.setTimeStamp((System.currentTimeMillis()/1000)+"");

		cpi.setPaySign(PayTools.createWXClientPayRequestSign(cpi,appSetting.getMchKey()));			
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = cpi;
		
		return jr;
		
	}
	
	/**
	 * 退款申请
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/refund", method = RequestMethod.POST)
	public Object wxPostRefund(HttpServletRequest request) throws Exception{		

		long userId = Long.parseLong(request.getHeader("userId"));
		
		Order requestOrder = Tools.getRequestObject(request, Order.class);

		String orderId = requestOrder.getOrderId();//订单号

		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order || order.getUserId()!=userId){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		
		if (System.currentTimeMillis() - order.getCreatedTime() > 25*24*3600*100) {
			jr.respCode = CodeConstants.ORDERCLOSED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERCLOSED_MSG);
			return jr;
		}
		
		//只有发货后才可以申请退款
		if(order.getOrderState() < 2){
			jr.respCode = CodeConstants.REFUNDSTATEERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.REFUNDSTATEERROR_MSG);
			return jr;
		}
		
		requestOrder.setRefundState(1);
		requestOrder.setRefundTime(System.currentTimeMillis());
		orderService.updateOrder(requestOrder);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		
		return jr;
	}
	/**
	 * 退款申请修改
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/refund", method = RequestMethod.PUT)
	public Object wxPutRefund(HttpServletRequest request) throws Exception{		

		long userId = Long.parseLong(request.getHeader("userId"));
		
		Order requestOrder = Tools.getRequestObject(request, Order.class);

		String orderId = requestOrder.getOrderId();	

		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order || order.getUserId()!=userId){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		//只有发货后才可以申请退款
		if(order.getOrderState()==1){
			jr.respCode = CodeConstants.REFUNDAPPLYERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.REFUNDAPPLYERROR_MSG);
			return jr;
		}
		
		orderService.updateOrder(requestOrder);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		
		return jr;
	}
	
	/**
	 * 撤销退款申请
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/refund/del", method = RequestMethod.PUT)
	public Object wxDelRefund(HttpServletRequest request) throws Exception{		

		long userId = Long.parseLong(request.getHeader("userId"));
		
		Order requestOrder = Tools.getRequestObject(request, Order.class);

		String orderId = requestOrder.getOrderId();	

		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order || order.getUserId()!=userId){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		if(order.getRefundState()!=1){
			jr.respCode = CodeConstants.REFUNDSTATEERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.REFUNDSTATEERROR_MSG);
			return jr;
		}
		
		requestOrder.setRefundState(0);
		requestOrder.setRefundImg(null);
		requestOrder.setRefundMessage(null);
		requestOrder.setRefundReason(null);
		requestOrder.setRefundMoney(0d);
		orderService.updateOrder(requestOrder);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		
		return jr;
	}
	
	/**
	 * 删除订单
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/del", method = RequestMethod.PUT)
	public Object delete(HttpServletRequest request) throws Exception{		

		long userId = Long.parseLong(request.getHeader("userId"));
		
		Order requestOrder = Tools.getRequestObject(request, Order.class);
		requestOrder.setState(1);
		String orderId = requestOrder.getOrderId();

		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order || order.getUserId()!=userId){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		orderService.updateOrder(requestOrder);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		
		return jr;
	}
	
	/**
	 * 取消订单
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/cancel", method = RequestMethod.PUT)
	public Object cancel(HttpServletRequest request) throws Exception{		

		long userId = Long.parseLong(request.getHeader("userId"));
		
		Order requestOrder = Tools.getRequestObject(request, Order.class);
		String orderId = requestOrder.getOrderId();	

		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order || order.getUserId()!=userId){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		if(order.getOrderState() > 0){
			jr.respCode = CodeConstants.ORDERSTATEERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERSTATEERROR_MSG);
			return jr;
		}
		requestOrder.setOrderState(-1);
		orderService.updateOrder(requestOrder);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		
		return jr;
	}
	
	/**
	 * 确认收货(订单完成)
	 * @param request
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/orders/finish", method = RequestMethod.PUT)
	public Object finish(HttpServletRequest request) throws Exception{		

		long userId = Long.parseLong(request.getHeader("userId"));
		
		Order requestOrder = Tools.getRequestObject(request, Order.class);

		String orderId = requestOrder.getOrderId();	

		JsonResult jr = new JsonResult();
		
		Order order = orderService.queryByOrderId(orderId);
		
		if(null==order || order.getUserId()!=userId){
			jr.respCode = CodeConstants.ORDERNOTEXIST_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERNOTEXIST_MSG);
			return jr;
		}
		
		if(order.getOrderState() != 2 && order.getRefundState() != 0){
			jr.respCode = CodeConstants.ORDERERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.ORDERERROR_MSG);
			return jr;
		}
		
		requestOrder.setOrderState(3);
		requestOrder.setCommentState(1);
		orderService.updateOrder(requestOrder);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		
		return jr;
	}
	
}
